/**首页 */
import { PieChartOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Layout, Menu } from 'antd';
import React, { useState, useEffect } from 'react';
import { useHistory } from 'umi';
import PersonalCenter from './components/PersonalCenter';
import Nav from './components/nav';
import { loginApi } from '@/api/login';
import { firstLevelMenuUrl, otherMenuUrl } from '@/urls/url';
import { menuItem } from './interface';
import styles from './index.less';

const { Header, Content, Footer, Sider } = Layout;

type MenuItem = Required<MenuProps>['items'][number];

function getItem(
  label: React.ReactNode,
  key: React.Key,
  icon?: React.ReactNode,
  children?: MenuItem[],
): MenuItem {
  return {
    key,
    icon,
    children,
    label,
  } as MenuItem;
}

const App: React.FC = (props) => {
  const history = useHistory();
  //侧边框收缩
  const [collapsed, setCollapsed] = useState(false);
  //导航菜单
  const [menuItem, setMenuItem] = useState<menuItem>({
    menuId: '',
    menuName: '',
    menuUrl: '',
    parentId: '',
  });
  const [otherMenuItem, setOtherMenuItem] = useState<menuItem[]>([]);
  const getMenuitem = async () => {
    const {
      data: { data },
    } = await loginApi(firstLevelMenuUrl);
    if (data) {
      setMenuItem(data[0]);
      let obj = data[0].menuId;
      const res = await loginApi(otherMenuUrl, { parentId: obj });
      setOtherMenuItem(res.data.data);
    }
  };
  useEffect(() => {
    getMenuitem();
  }, []);

  const item2 = otherMenuItem.map(
    (item: { menuName: string; menuUrl: string }) =>
      getItem(item.menuName, item.menuUrl),
  );
  const items = [
    getItem(menuItem.menuName, menuItem.menuUrl, <PieChartOutlined />, item2),
  ];

  const switchRouter: MenuProps['onClick'] = (e) => {
    history.push(e.key);
  };

  return (
    <>
      <Layout style={{ minHeight: '100vh' }}>
        <Sider
          collapsible
          collapsed={collapsed}
          onCollapse={(value) => setCollapsed(value)}
        >
          <div className={styles.logo}>招行-勤学后台管理</div>
          <Menu
            theme="dark"
            defaultOpenKeys={['/activityManagement']}
            defaultSelectedKeys={['/createActivity']}
            mode="inline"
            items={items}
            onClick={switchRouter}
          />
        </Sider>
        <Layout className={styles['site-layout']}>
          <Header
            className={styles['site-layout-background']}
            style={{ padding: 0 }}
          >
            <PersonalCenter />
          </Header>
          <Nav />

          <Content style={{ margin: '20px 16px' }}>
            <div
              style={{ minHeight: 650 }}
            >
              {props.children}
            </div>
          </Content>
          <Footer style={{ textAlign: 'center' }}>
            Ant Design ©2018 Created by Ant UED
          </Footer>
        </Layout>
      </Layout>
    </>
  );
};

export default App;
